package com.tensquare.notice.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import com.tensquare.notice.handler.MyWebSocketHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;

import java.util.HashMap;

/**
 * 文章推送
 */
public class SysNoticeListener implements ChannelAwareMessageListener {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        try {
//            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            System.out.println("有订阅消息-------");
            //获取用户id，可以通过队列名称获取
            String queueName = message.getMessageProperties().getConsumerQueue();
            String userId = queueName.substring(queueName.lastIndexOf("_") + 1);

            io.netty.channel.Channel wsChannel = MyWebSocketHandler.userChannelMap.get(userId);
            //出现异常会一直发消息
//        int i = 1/0;
            //判断用户是否在线
            if (wsChannel != null) {
//            Integer messageCount = message.getMessageProperties().getMessageCount();
                //如果连接不为空，表示用户在线
                //封装返回数据
                HashMap<String, Object> countMap = new HashMap<>();
                countMap.put("sysNoticeCount", 1);
                Result result = new Result(true, "查询成功", StatusCode.OK, countMap);

                // 把数据通过WebSocket连接主动推送用户
                wsChannel.writeAndFlush(new TextWebSocketFrame(MAPPER.writeValueAsString(result)));
            }
        } catch (Exception e) {
            System.err.println("消息发送失败！");
//            e.printStackTrace();
        }
    }
}
